package org.harsh.transmission.client;

import com.ruoyi.system.service.ISysConfigService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import lombok.extern.slf4j.Slf4j;
import org.harsh.transmission.common.*;
import org.harsh.transmission.common.codec.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
    private static long totalWriteLimit;
    private static long totalReadLimit;
    private long channelWriteLimit;
    private long channelReadLimit;

    @Autowired
    private PlainMsgCodec plainMsgCodec;
    @Autowired
    private FileMsgCodec fileMsgCodec;
    @Autowired
    private ISysConfigService sysConfigService;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        long channelWriteLimit = 16384l;
        long channelReadLimit = 16384l;
        String tmpWriteStr = sysConfigService.selectConfigByKey("trans.write.channelLimit");
        String tmpReadStr = sysConfigService.selectConfigByKey("trans.read.channelLimit");
        if(tmpWriteStr != null)
            channelWriteLimit = Long.valueOf(tmpWriteStr);
        if(tmpReadStr != null)
            channelReadLimit = Long.valueOf(tmpReadStr);
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(GlobalTraffic.getInstance())
                .addLast("channelTraffic", new ChannelTrafficShapingHandler(channelWriteLimit, channelReadLimit, 1));
        pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS))
                .addLast(new LengthFieldBasedFrameDecoder(14000, 0, 4, 0,4))
                .addLast(new LengthFieldPrepender(4))
                .addLast("cryptCodec", new CryptMsgPackCodec())
                .addLast("msgPackDecoder",new MsgPackDecoder())
                .addLast("msgPackEncoder",new MsgPackEncoder())
                .addLast("ecdhHandler",new EcdhClientHandler());
        pipeline.addLast("plainMsgCodec", plainMsgCodec)
                .addLast("fileCodec", fileMsgCodec);
    }
}
